package com.lqh.flutterModuleFirst

import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor

class StartFlutterActivity : AppCompatActivity() {
    lateinit var flutterEngine: FlutterEngine
    private lateinit var communicationHelper: FlutterCommunicationHelper

    companion object {
        private const val TAG = "StartFlutterActivity"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.start_flutter_activity)

        // 实例化Flutter引擎
        flutterEngine = FlutterEngine(this)

        // 开发环境使用release版本的Flutter模块
        // 直接使用编译后的代码，不连接开发服务器
        flutterEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )

        // 设置通讯 - 在引擎初始化后立即设置
        communicationHelper = FlutterCommunicationHelper(this, flutterEngine)
        communicationHelper.setupChannels()

        // 缓存Flutter引擎
        FlutterEngineCache
            .getInstance()
            .put("my_engine_id", flutterEngine)

        val myButton = findViewById<Button>(R.id.my_btn)
        myButton.setOnClickListener {
            startActivity(
                FlutterActivity
                    .withCachedEngine("my_engine_id")
                    .build(this)
            )
        }

        Log.d(TAG, "StartFlutterActivity initialized with communication channels")
    }

    override fun onDestroy() {
        super.onDestroy()
        flutterEngine.destroy()
        Log.d(TAG, "StartFlutterActivity destroyed")
    }
}